<?php

namespace App\Console\Commands;

use App\Jobs\BlockPool\LeaderJob;
use Illuminate\Console\Command;
use App\Models\GiveU;
use App\Models\GiveURewad;
use App\Models\Account;
use Illuminate\Support\Facades\DB;

class GiveUU extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'giveu';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '抢U';

    /**
     * Create a new command instance.
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $giveu = Giveu::where('status', 0)->get();
        foreach ($giveu as  $v) {
            if (time() - strtotime($v['update_at']) >= 42000) {
                $rewardAccount = Account::firstOrCreate([
                    'user_id' => $v->user_id,
                    'coin_id' => 1
                ])->refresh();
                DB::transaction(function () use ($v, $rewardAccount) {
                    $v->update_at = date("Y-m-d H:i:s", (strtotime($v['update_at']) + 42000));
                    $v->status = 1;
                    $v->save();

                    $giveUreward = new GiveURewad;
                    $giveUreward->reward = intval($v->num / 10) * 10 * $v->rate;
                    $giveUreward->user_id = $v->user_id;
                    $giveUreward->num = $v->num;
                    $giveUreward->status = 1;
                    $giveUreward->update_at = $v->update_at;
                    $giveUreward->save();

                    $account = Account::lockForUpdate()->find($rewardAccount->id);
//                    $account->availableIncrement($giveUreward->reward);
                    $account->disabledDecrement($giveUreward->num);
                    $account->availableIncrement(bcadd($giveUreward->num, $giveUreward->reward));
                    $account->type = '抢U奖励释放';
                    $account->action_id = $v->id;
                    $account->save();

                    (new LeaderJob($giveUreward))->handle();
                    // LeaderJob::dispatch($giveUreward)->onQueue('recommend');
                });
            }
        }
    }
}
